import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:audioplayers/audioplayers.dart';
import 'dart:math';

import 'package:speed_random/pages/home/rand_com/logic.dart';
import 'package:speed_random/pages/home/rand_com/state.dart';


class ViewBodySpinWheel extends StatefulWidget {
  final RandComLogic logic;
  final RandComState state;

  const ViewBodySpinWheel({Key? key, required this.logic, required this.state})
      : super(key: key);

  @override
  State<ViewBodySpinWheel> createState() => _ViewBodySpinState();
}

class _ViewBodySpinState extends State<ViewBodySpinWheel>
    with SingleTickerProviderStateMixin {
  final resultText = "".obs; //结果文本
  final resultindex = 0.obs; //结果索引，所以因为取索取颜色。
  var rotationAngle = 0.0.obs;
  var isSpinning = false.obs;
  var prizes = <String>[];
  AnimationController? _animationController;

  final colorslist = <Color>[
    Colors.red,
    Colors.blue,
    Colors.green,
    Colors.yellow,
    Colors.orange,
    Colors.purple,
    Colors.indigo,
    Colors.teal,
    Colors.cyan,
    Colors.lime,
    Colors.amber,
    Colors.pink,
    Colors.brown,
    Colors.deepPurple,
    Colors.lightBlue,
    Colors.lightGreen,
    Colors.deepOrange,
    Colors.blueGrey,
    Colors.redAccent,
    Colors.blueAccent,
    Colors.greenAccent,
    Colors.yellowAccent,
    Colors.orangeAccent,
    Colors.purpleAccent,
    Colors.indigoAccent,
  ];

  final colors = <Color>[];

  @override
  void initState() {
    super.initState();
    prizes = widget.state.randComArgs.value.list.split(",");
    for (int i = 0; i < prizes.length; i++) {
      colors.add(colorslist[i % colorslist.length]);
    }
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
    );
  }

  @override
  void dispose() {
    _animationController?.dispose();
    super.dispose();
  }

Future<void> startSpin() async {
    if (isSpinning.value) return;

    isSpinning.value = true;
    widget.state.randomNumbers.value = []; // Clear previous result
    resultText.value = "";
    // Generate random result
    widget.logic.generateRandomNumbersRunOne(isSaveCache: true);
    widget.state.isRun.value = 1;
    widget.logic.payRunMp3();
   // widget.state.randomNumbers.value=["1"];
    final result = widget.state.randomNumbers.value.first;
     //print("result:$result");
    // Find the index of the winning prize (0-based)
    var winningIndex = prizes.indexWhere((prize) => prize == result);
    if (winningIndex == -1) {
      isSpinning.value = false;
      return;
    }
    resultindex.value=winningIndex;
    // 这两步调整 位置，让中奖的位置在正常位置上
    winningIndex=winningIndex+1;
    winningIndex=-winningIndex;


    // Correct angle calculation:
    final sectorAngle = 2 * pi / prizes.length;
    // 目标角度是获胜扇区的中心
    // 我们减去 pi/2，因为轮子从顶部的位置 1 开始（90 度）
    final targetAngle = (winningIndex * sectorAngle + sectorAngle/2- pi/2 ) % (2 * pi);
    //print("targetAngle:$targetAngle");
    // Add 5 full rotations (10π radians) before stopping at target
    const fullRotations = 10 * pi;
    final finalAngle = fullRotations + targetAngle;
    //print("finalAngle:$finalAngle");
    // Create the animation
    final animation = Tween<double>(
      begin: 0, // 总是从0开始旋转
      end: finalAngle,
    ).animate(CurvedAnimation(
      parent: _animationController!,
      curve: Curves.easeOutCubic,
    ));

    final items = widget.state.randComArgs.value.list.split(",");
    final random = Random();
    int lastUpdateTime = DateTime.now().millisecondsSinceEpoch;
    const updateInterval = 100; // 每 100 毫秒更新一次

    animation.addListener(() {
      rotationAngle.value = animation.value;
      // 控制更新频率
      final currentTime = DateTime.now().millisecondsSinceEpoch;
      if (currentTime - lastUpdateTime > updateInterval) {
        final randomIndex = random.nextInt(items.length);
        resultText.value = items[randomIndex];
        lastUpdateTime = currentTime;
      }
    });

    _animationController!.reset();
    _animationController!.forward();


    _animationController!.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        isSpinning.value = false;
        widget.logic.payRunMp3(type: "stop");

        // Normalize to prevent angle overflow
        rotationAngle.value = targetAngle;
        resultText.value = result;
      }
    });

  }

  @override
  Widget build(BuildContext context) {
    widget.state.funStart = startSpin;

    return Card(
        color:widget.state.randComArgs.value.colorPagebg,
        // 使用 Obx 响应式组件
        child:Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [



                        Expanded(
              child: Center( // 使用 Center 组件将内容居中
                child: SizedBox(

                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Obx(() => Text(
                         "${resultText.value}", // 用空格分隔更清晰
                        style: TextStyle(
                            fontSize: 50,
                           // fontWeight: FontWeight.w600,
                            color: widget.state.randComArgs.value.colorPageText,
                            letterSpacing: 1.2
                        ),
                        textAlign: TextAlign.center, // 文字居中对齐
                      )),
                    ],
                  )
                ),
              ),
            ),


            // Spin wheel
            Obx(() => Stack(
              alignment: Alignment.center,
              children: [
            Transform.rotate(
            angle: rotationAngle.value,
              child: Container(
                width: 350,
                height: 350,
                decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    gradient: RadialGradient(
                      colors: [Colors.grey[300]!, Colors.grey[200]!],
                      stops: [0.3, 1.0],
                    ),
                    boxShadow: [
                BoxShadow(
                color: Colors.black.withOpacity(0.2),
                spreadRadius: 2,
                blurRadius: 10,
                offset: const Offset(0, 5),
                )],
              ),
              child: CustomPaint(
                painter: _WheelPainter(
                  prizes: prizes,
                  colors: colors,
                  selectedIndex: -1,
                ),
              ),
            ),
            ),

            // Center fixed point
            Container(
              width: 30,
              height: 30,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.white,
                border: Border.all(color: Colors.black, width: 2),
              ),
            ),

            // Wheel pointer - stays fixed
            Container(
              width: 30,
              height: 60,
              child: CustomPaint(
                painter: _ArrowPainter(),
              ),
            ),
          ],
        )),
            SizedBox(height: 20,)

    ],
    ),
    ));
  }
}

// Keep your existing _WheelPainter and _ArrowPainter classes




class _WheelPainter extends CustomPainter {
  final List<String> prizes;
  final List<Color> colors;
  final int selectedIndex;

  _WheelPainter({
    required this.prizes,
    required this.colors,
    required this.selectedIndex,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width / 2;
    final sectorAngle = 2 * pi / prizes.length;

    final paint = Paint()
      ..style = PaintingStyle.fill;
    final textPainter = TextPainter(
      textDirection: TextDirection.ltr,
      textAlign: TextAlign.center,
    );

    for (int i = 0; i < prizes.length; i++) {
      // Draw sector
      paint.color = colors[i];
      canvas.drawArc(
        Rect.fromCircle(center: center, radius: radius),
        i * sectorAngle,
        sectorAngle,
        true,
        paint,
      );

      // Draw sector border
      paint.color = Colors.white;
      paint.style = PaintingStyle.stroke;
      paint.strokeWidth = 1.0;
      canvas.drawArc(
        Rect.fromCircle(center: center, radius: radius),
        i * sectorAngle,
        sectorAngle,
        true,
        paint,
      );
      paint.style = PaintingStyle.fill;

      // Draw text
      final angle = i * sectorAngle + sectorAngle / 2;
      canvas.save(); // 保存画布状态
      canvas.translate(center.dx, center.dy); // 移动画布原点到圆心
      canvas.rotate(angle); // 旋转画布到扇形中心角度

      textPainter.text = TextSpan(
        text: prizes[i].length>6?prizes[i].substring(0, 6):prizes[i],
        style: TextStyle(
          color: Colors.white,
          fontSize: radius * 0.10, // 稍微增大字号
          fontWeight: FontWeight.bold,
        ),
      );
      textPainter.layout();

      // 调整文字位置到扇形中心（旋转后坐标系已改变）
      final textX = radius * 0.4; // 从0.5改为0.65，离中心更远
      final textY = -textPainter.height / 2; // 垂直居中
      textPainter.paint(canvas, Offset(textX, textY));

      canvas.restore(); // 恢复画布原始状态
    }
  }
  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

class _ArrowPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;

    final path = Path();
    path.moveTo(size.width / 2, 0);
    path.lineTo(0, size.height);
    path.lineTo(size.width, size.height);
    path.close();

    canvas.drawPath(path, paint);

    // Add some decoration
    paint.color = Colors.white;
    canvas.drawCircle(
      Offset(size.width / 2, size.height * 0.7),
      size.width * 0.1,
      paint,
    );
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}